package com.conversationboard.controller;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.authenticator.AuthenticationCookie;

/* Now uses Java EE 6 programmatic login.
 * 
 * @author Keith Watson */

@WebServlet(name = "LoginControllerServlet", urlPatterns = "/LoginControllerServlet")
public class LoginControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -4672198715253906039L;


	/* This is sendRedirected from the various 'front' pages, when it discovers you're not logged in, but you
	 * don't have a cookie. It logs you in and then sends you back to where you came from. */

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");

			String referrer = "";

			if (request.getParameter("autologin").equalsIgnoreCase("true")) {
				referrer = request.getParameter("referrer");

				String userName = AuthenticationCookie.getUserName(request);
				String password = AuthenticationCookie.getPassword(request);

				request.login(userName, password);
			}

			if (referrer == null) {
				RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
				dispatcher.forward(request, response);
			} else {
				RequestDispatcher dispatcher = request.getRequestDispatcher(referrer);
				dispatcher.forward(request, response);
			}

		} catch (ServletException e) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("Pages/login-failed.jsp");
			dispatcher.forward(request, response);
		}

	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		try {
			String userName = request.getParameter("username");
			String password = request.getParameter("password");

			request.login(userName, password);

			/* If you successfully logged in, and you wanted 'remembered', then store your username and
			 * password as cookies */

			if ((request.getParameter("rememberMeCheckBox") != null) && (request.getUserPrincipal() != null)) {
				AuthenticationCookie.storeCookie(userName, password, request, response);
			}

			RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
			dispatcher.forward(request, response);

		} catch (ServletException e) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("Pages/login-failed.jsp");
			dispatcher.forward(request, response);
		}

	}

}
